var map;
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();

var customersArray = []; 	//array of all customers - input
var distancesArray = [];	//array of pairs of distance - calculate
var routesArray = [];		//array of pairs of routes - calculate

var directionsRenderersArray = []; //array of directionsRenderers

function Customer(cid, latLng, from, to) {
	this._cid = cid;
	this._latLng = latLng;
	this._from = from;
	this._to = to;
}

$(document).ready(function(){
	map = new google.maps.Map(document.getElementById("map_canvas"),{
		zoom: 12,
		center: new google.maps.LatLng(1.3603333, 103.8133333),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	});
	
	var pageIsDepot = $('#pageIsDepot').html(); 
	
	$("#dialogmap" ).dialog({ width: 930 });
	
	$("#buttonviewmap").click(function(){
		$("#dialogmap" ).dialog('open');
	});
	
	$('.marker').each(function(){
		var cid = parseInt($(this).find('.markerID').first().html());
		var lat = parseFloat($(this).find('.markerLat').first().html());
		var lng = parseFloat($(this).find('.markerLng').first().html());
		var title = $(this).find('.markerTitle').first().html();
		var isDepot = $(this).find('.markerIsDepot').first().html();
		var latLng = new google.maps.LatLng(lat,lng);
		if (isDepot == pageIsDepot) {
			var marker = new google.maps.Marker({
				position: latLng,
				title: title,
				//animation: google.maps.Animation.DROP,
				map: map
			});
		}
		customersArray.push(new Customer(cid, latLng, 0, 0));
	});
	
	$(".formsubmit").click(function(){
		var thisform = $(this).parents('form').first();
		var title = thisform.find('input[name="name"]').first().val();
		var postalCode = thisform.find('input[name="postalCode"]').first().val();
		var address = 'Singapore ' + postalCode;
		if ($(this).hasClass('editform')) {
			var oldPostalCode = thisform.find('input[name="oldPostalCode"]').first().val();
			if (oldPostalCode == postalCode) {
				thisform.submit();
				return;
			}
		}
		geocoder.geocode({ 'address': address }, function (results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var latLng = results[0].geometry.location;
				var lat = parseFloat(latLng.lat());
				var lng = parseFloat(latLng.lng());
				thisform.find('input[name="lat"]').first().val(lat);
				thisform.find('input[name="lng"]').first().val(lng);
				
				var count = customersArray.length * 2;
				for (var i in customersArray) {
					var request1 = {
						origin: latLng, 
						destination: customersArray[i]._latLng,
						// waypoints: [
							// {
								// location: "...",
								// stopover: true
							// }
						// ],
						// optimizeWaypoints: true,
						travelMode: google.maps.DirectionsTravelMode.DRIVING
					};
					var request2 = {
							origin: customersArray[i]._latLng, 
							destination: latLng,
							// waypoints: [
								// {
									// location: "...",
									// stopover: true
								// }
							// ],
							// optimizeWaypoints: true,
							travelMode: google.maps.DirectionsTravelMode.DRIVING
						};
					(function(i){
						directionsService.route(request1, function(result, status) {
							if (status == google.maps.DirectionsStatus.OK) {
								customersArray[i]._to = parseInt(result.routes[0].legs[0].distance.value);
								count--;
							}
						});
					})(i);
					(function(i){
						directionsService.route(request2, function(result, status) {
							if (status == google.maps.DirectionsStatus.OK) {
								customersArray[i]._from = parseInt(result.routes[0].legs[0].distance.value);
								count--;
							}
						});
					})(i);
				}
				var checkFinished = setInterval(function(){
					if (count == 0) {
						clearInterval(checkFinished);
						var distances = '';
						for (var i in customersArray) {
							distances += customersArray[i]._cid + ' ' + customersArray[i]._from + ' ' + customersArray[i]._to + '-';
						}
						distances = distances.substring(0,distances.length-1);
						thisform.find('input[name="distances"]').first().val(distances);
						thisform.submit();
					}
				},500);
			}
			else {
				alert('The input Postal Code is invalid. Please enter again.');
			}
		});
	});
});